﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Ornament.Domain;
using Products.Databases;

namespace Products
{
    public class Product : DomainObject<Guid>
    {
        private IList<ProductVersion> versions;

        [Required, Display(Name = "Product Name")]
        public virtual string Name { get; set; }

        [StringLength(100,
            ErrorMessage = "Memo's length between 100", MinimumLength = 0)]
        public virtual string Memo { get; set; }

        public virtual ReadOnlyCollection<ProductVersion> Versions
        {
            get { return new ReadOnlyCollection<ProductVersion>(versions ?? (new List<ProductVersion>())); }
        }

        public virtual ProductVersion Find(Guid versionId)
        {
            return Versions.FirstOrDefault(version => version.Id == versionId);
        }

        protected override int CreateHashCode()
        {
            return Id.GetHashCode();
        }

        public virtual ProductVersion CreateNewVersion(string versionName, double order)
        {
            if (versionName == null)
            {
                throw new ArgumentNullException("versionName");
            }
            var result = new ProductVersion(versionName, order, this);
            (versions ?? (new List<ProductVersion>())).Add(result);
            return result;
        }

        public virtual IList<ProductVersion> GetVersions(DatabaseObject dbObj)
        {
            if (dbObj == null) throw new ArgumentNullException("dbObj");
            IEnumerable<ProductVersion> result = from version in versions
                                                 where version.OrderValue >= dbObj.CreateVersion.OrderValue
                                                 select version;
            return result.ToList();
        }

        public virtual ProductVersion GetVersion(string versionName)
        {
            if (versionName == null) throw new ArgumentNullException("versionName");
            IEnumerable<ProductVersion> result = from version in versions
                                                 where version.Name.ToLower() == versionName.ToLower()
                                                 select version;
            return result.FirstOrDefault();
        }
    }
}